/*
 * Copyright (C) 2010 Imavis Srl
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published
 * by the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package com.imavis.avimuxer;

import java.util.Date;

/**
 * Calculates the average frame rate from the given timestamps.
 *
 * @author Andrea Gualano
 */
final class FramerateAverager {
    private int counter;
    private Date first;
    private Date last;

    public FramerateAverager() {
        this.counter = 0;
    }

    public void update(Date timestamp) {
        if (timestamp == null) {
            throw new NullPointerException("Timestamp cannot be null");
        }
        if (counter == 0) {
            first = timestamp;
        } else {
            last = timestamp;
        }
        counter++;
    }

    public int getRate() {
        if (counter > 1 && !last.equals(first)) {
            int frames = counter - 1;
            double rate = 1000.0 * frames / (last.getTime() - first.getTime());
            final int intRate = (int) (rate + 0.5);
            return intRate <= 0 ? 1 : intRate;
        } else {
            return 25;
        }
    }
}
